package com.itheima.xx.proxy_l;

import com.itheima.xx.web.UserService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Description:
 *
 * @author codermao
 * @date 2023/10/25 09:30
 */
public class Test01 {
    public static void main(String[] args) {

        //获取UserService实现类的加载器
        Class<UserService> userServiceClass = UserService.class;
        ClassLoader loader = userServiceClass.getClassLoader();
        //获取被代理类的接口
        Class<?>[] interfaces = {UserService.class};

        //InvocationHandler 处理接口中的抽象方法
        UserService userService = (UserService)Proxy.newProxyInstance(loader, interfaces, new InvocationHandler() {
            /**
             *  所有代理对象调用的方法，执行是都会经过invoke
             *  因此如果要对某个方法进行代理增强，就可以在这个invoke方法中进行定义
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String name = method.getName();
                long start = System.currentTimeMillis();
                if("login".equals(name)){
                    //登录
                    System.out.println("登录");
                    Thread.sleep(3000);
                }else if("delete".equals(name)){
                    //删除
                    System.out.println("删除");
                    Thread.sleep(4000);
                }else if("query".equals(name)){
                    //查询
                    System.out.println("查询");
                    Thread.sleep(5000);
                }
                long end = System.currentTimeMillis();
                System.out.println(name+"耗时："+(end-start));
                return null;
            }
        });


        //
        userService.login();
        userService.delete();
        userService.query();
    }
}
